import person from '@/models/person';
import password from '@/models/password';
import holiday from '@/models/holiday';
import { ObjectId } from 'mongodb';
import dayjs from 'dayjs';

// 新增、修改人员信息
export const syncEditPerson = async (params) => {
  const { isEdit, _id, role, ...otherParams } = params;
  if (isEdit) {
    // 编辑
    const res = await person.update({ ...otherParams, role: new ObjectId(role) }, { _id: new ObjectId(_id) });
    return res;
  }
  // 新增
  const res: any = await person.insert({ ...otherParams, role: new ObjectId(role) });
  // 给个初始密码123456
  const res1 = password.insert({ personId: res.insertedId, name: params.name as string, password: 'e10adc3949ba59abbe56e057f20f883e' });
  return res1;
};

// 人员列表
export const syncGetPersons = async (params: { _id: string }) => {
  const { _id } = params;
  const query: any = {};
  if (_id) {
    query._id = new ObjectId(_id);
  }
  query.name = { $ne: 'admin' };
  query.role = { $in: [new ObjectId('64feec8ae6de3ece9c58b582'), new ObjectId('64feec8ae6de3ece9c58b581')] };
  const res = await person.getListJoin(query);
  return res;
};

// 人员删除
export const syncDeletePerson = async (params) => {
  await person.deleteOne({ _id: new ObjectId(params._id) });
  await password.deleteOne({ id: new ObjectId(params._id) });
  return true;
};

// 修改密码
export const updatePwd = async (params) => {
  await password.update({ ...params, personId: new ObjectId(params.personId) }, { personId: new ObjectId(params.personId) });
  return true;
};

// 获取法定节假日
export const getHoliday = async () => {
  // 获取今年和第二年
  const cur_year = `${dayjs().year()}`;
  const next_year = `${dayjs().add(1, 'year').year()}`;
  const res = await holiday.getList({
    year: {
      $in: [cur_year, next_year],
    },
  });
  return res;
};

// 设置法定节假日
export const setHoliday = async (params) => {
  const res = await fetch(`https://timor.tech/api/holiday/year/${params.year as string}`);
  return res.json().then((r) => {
    holiday.insert({ holiday: r.holiday, year: params.year });
  });
};
